<template>
    <div class="manage">
        <div class="manage-header">
            <el-form :model="searchForm" :inline="true" label-width="90px">
                <el-form-item label="名称/标识">
                    <el-input v-model="searchForm.name" @input="search" clearable size="small" placeholder="支持角色名称或标识"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="add" size="small">新增角色</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="common-table">
            <el-table
                stripe
                height="90%"
                :data="tableData"
                style="width: 100%">
                <el-table-column
                    prop="name"
                    label="标识"
                    width="180">
                </el-table-column>

                <el-table-column prop="label" label="名称" width="180"></el-table-column>
                <el-table-column prop="description" label="简介"></el-table-column>

                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" @click="menu(scope.row, 1)" size="mini">分配权限</el-button>
                        <el-button type="primary" @click="menu(scope.row, 2)" size="mini">分配菜单</el-button>
                        <el-button type="primary" @click="handleEdit(scope.row)" size="mini">编辑</el-button>
                        <el-button @click="handleDelete(scope.row)" type="danger" size="mini">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-dialog
            :title="typeof form.id === 'number' ? '编辑角色' : '新增角色'"
            :visible.sync="dialogVisible"
            @close="onClosed()"
            width="1200">
            <el-form ref="form" :model="form" :rules="rules" :inline="true"  label-width="100px">
                <el-form-item label="标识" prop="name">
                    <el-input v-model="form.name" size="small" style="width: 200px" placeholder="请输入标识"></el-input>
                </el-form-item>

                <el-form-item label="名称" prop="label">
                    <el-input v-model="form.label" size="small" style="width: 200px" placeholder="请输入名称"></el-input>
                </el-form-item>

                <el-form-item label="简介" prop="description">
                    <el-input type="textarea" size="small" style="width: 510px" :rows="3" v-model="form.description" placeholder="请输入简介"></el-input>
                </el-form-item>
            </el-form>

            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="dialogVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="handleRole">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog
            :title="type === 1 ? `在给 ${form.name} 分配权限` : `在给 ${form.name} 分配菜单`"
            :visible.sync="menuDialogVisible"
            @opened="dialogOpened"
            @closed="dialogClosed"
            width="1200">
            <el-card shadow="never">
                <el-tree
                    :data="treeData"
                    show-checkbox
                    default-expand-all
                    node-key="id"
                    ref="tree"
                    :props="defaultProps">
                </el-tree>
            </el-card>

            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="menuDialogVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="doMenu">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

import { getRoleList, addRole, editRole, deleteRole, getInit, assignPermissions, assignMenus } from "@/api/role"

export default {
    data() {
        return {
            dialogVisible: false,
            menuDialogVisible: false,
            type: 0,
            form: {
                id: '',
                name: '',
                label: '',
                description: ''
            },
            searchForm: {
                name: ''
            },
            params: {
                data: {
                    permissions: [],
                    menus: []
                }
            },
            treeData: [],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            defaultCheckedKeys: [],
            tableData: [],
            total: 0,
            rules: {
                name: [
                    {required: true, message: '请输入标识', trigger: 'blur'}
                ],
                label: [
                    {required: true, message: '请输入名称', trigger: 'blur'}
                ]
            }
        }
    },
    created() {
        this.getInit()
        this.getList()
    },
    methods: {
        getInit() {
            getInit().then(({ data }) => {
                console.log(data)
                this.params.data = data.data
            })
        },
        getList() {
            getRoleList({params: {...this.searchForm}}).then(({ data }) => {
                // console.log(data)
                if (typeof data.data !== 'string') {
                    this.tableData = data.data
                }
            })
        },
        search(val) {
            if (val.length) {
                this.tableData = this.tableData.filter((item) => {
                    return item.label.indexOf(val) !== -1 || item.name.indexOf(val) !== -1
                })
            } else {
                this.getList()
            }
        },
        add() {
            this.dialogVisible = true
            this.form.id = ''
        },
        handleRole() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    if (this.form.id) {
                        editRole(this.form.id, this.form).then(({ data }) => {
                            if (data.code === 200) {
                                this.$message.success('编辑角色成功')
                            } else {
                                this.$message.error(data.data)
                            }
                        })
                    } else {
                        addRole(this.form).then(({ data }) => {
                            if (data.code === 201) {
                                this.$message.success(data.data)
                            } else {
                                this.$message.error(data.data)
                            }
                        })
                    }

                    this.$refs.form.resetFields()
                    this.getList()
                    this.dialogVisible = false
                }
            })
        },
        menu(row, type) {
            this.form = JSON.parse(JSON.stringify(row))
            this.type = type

            if (type === 1) {
                this.treeData = this.params.data.permissions
                this.defaultCheckedKeys = row.permissions.map((item) => item.id)
            } else {
                this.treeData = this.params.data.menus
                this.defaultCheckedKeys = row.menus.map((item) => item.id)
            }

            console.log(this.defaultCheckedKeys)

            this.menuDialogVisible = true
        },
        doMenu() {
            let ids = this.$refs.tree.getCheckedKeys()

            if (this.type === 1) {
                assignPermissions(this.form.id, {ids: ids}).then(({data}) => {
                    if (data.code === 200) {
                        this.$message.success(data.data)
                        this.menuDialogVisible = false
                    } else {
                        this.$message.error(data.data)
                    }
                })
            } else {
                assignMenus(this.form.id, {ids: ids}).then(({data}) => {
                    if (data.code === 200) {
                        this.$message.success(data.data)
                        this.menuDialogVisible = false
                    } else {
                        this.$message.error(data.data)
                    }
                })
            }
        },
        handleEdit(row) {
            this.form = JSON.parse(JSON.stringify(row))
            this.dialogVisible = true
        },
        handleDelete(row) {
            this.$confirm('确认要删除该角色吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                deleteRole(row.id).then(({ data }) => {
                    // console.log(data)
                    if (data.code === 200) {
                        this.$message.success(data.data)
                    } else {
                        this.$message.error(data.data)
                    }
                    this.getList()
                })
            }).catch(() => {

            })
        },
        // 对话框关闭的回调
        onClosed() {
            this.$refs.form.resetFields()
        },
        dialogOpened() {
            this.$refs.tree.setCheckedKeys(this.defaultCheckedKeys)
        },
        dialogClosed() {
            this.$refs.tree.setCheckedKeys([])
            this.getList()
        }
    }
}
</script>

<style lang="less" scoped>
.manage {
    height: 90%;

    .manage-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .el-form {
            border: 1px solid #eee;
            border-radius: 5px;
            padding: 10px 0 0 10px;
            margin-bottom: 15px;
            width: 100%;
        }
    }

    .common-table {
        height: calc(100% - 62px);
        position: relative;

        .el-table::before {
            height: 0;
        }

        /deep/.el-table__header-wrapper {
            .cell {
                font-weight: normal;
                color: #666666;
            }
        }
    }
}
</style>
